// import TableFilterMixin from '@/mixins/TableFilterMixin'
import {
    VxeUI,
    VxeGrid,
    VxePager,
    type VxeColumnSlotTypes,
    type VxeGridDefines,
    type VxeGridMethods,
    type VxeGridPropTypes,
    type VxeGridProps,
    type VxeTableDataRow,
    type VxeColumnPropTypes,
    type SlotVNodeType,
    VxeTableDefines,
    type VxeTablePropTypes
} from 'vxe-table'
import { Component, Ref } from 'vue-facing-decorator'
import FilterRender, { type FilterDto } from './FilterRender'
import type { AnyObject } from '@/types'
import type { PageDto, PagesDto } from '@/api/types'
import { dateFormat } from '@/utils/util'

import type { JSX } from 'vue/jsx-runtime'
import { ref } from 'vue'

import PreviewImageOrPdf from '@/components/preview-media/PreviewImageOrPdf'
import useUserStore from '@/stores/user'
import ToolTipText from '@/components/tooltip-text/Index'
import type { ButtonType } from 'ant-design-vue/es/button'
import { Button, Empty, Form, message, Pagination, Popconfirm, Tag, Tooltip } from 'ant-design-vue'
import Icon, { CloudDownloadOutlined, CloudUploadOutlined, DeleteOutlined, DownloadOutlined, LoadingOutlined, MoreOutlined, PlusOutlined } from '@ant-design/icons-vue'
import router from '@/router'
import type { RouteLocationNormalizedLoadedGeneric } from 'vue-router'
import { ButtonMenuTypeCnEnum } from '@/const/enum'
import ImageR from '@/components/image/Index'

VxeUI.setConfig({
    emptyCell: '--'
})

export type ParamsButtonType = ButtonType & 'preview' & 'danger'

export interface TableRenderSlots<D> extends VxeColumnPropTypes.Slots<D> {
    default?: 'dateformat' | 'price' | 'unit' | 'color' | 'colorTag' | 'buttons' | 'enum' | 'idcardAge' | 'image' | ((params: VxeColumnSlotTypes.DefaultSlotParams<D>) => SlotVNodeType[] | SlotVNodeType) | null
}

export interface TableRenderColumnParamsButtons<D> {
    hidden?: (row: D) => boolean
    eventName?: string // 事件名
    text: string
    content?: string // 二次确认的提示内容
    type: ParamsButtonType
    event: (row: D) => void
    previewProp?: string // 预览的src的prop  type为preivew用 
    permission?: string
}

export interface TableRenderColumnOptions<D> extends VxeTableDefines.ColumnOptions<D> {
    params?: {
        tags: {
            [key: string | number]: string
        }
        colors: {
            [key: string | number]: string
        },
        format: string
        color: string
        buttons: TableRenderColumnParamsButtons<D>[]
        tooltip: {
            text: (row: D) => string | number
            content: (row: D) => string | number
            prefixIcon: typeof Icon
            suffixIcon: typeof Icon
            underline: boolean
            link: boolean
        },
        path: (row: D) => string,
        text: string
        srcList: (row: D) => string[]
    }
    slots?: TableRenderSlots<D>
}
export type TableRenderColumnTypes<D> = TableRenderColumnOptions<D>[]

export function renderSlotButtons<T>(that: any, position = ButtonMenuTypeCnEnum.列表后操作): TableRenderColumnParamsButtons<T>[] {
    if (!that?.$route) return []
    const route = that.$route as RouteLocationNormalizedLoadedGeneric
    // console.log('renderSlotButtons', route, route.meta)
    const btnChildren = route.meta.btnChildren as {
        menuName: string;
        path: string;
        btnPosition: string;
        btnStyle: ParamsButtonType;
        btnEvent: string;
    }[]
    return btnChildren?.filter(item => item.btnPosition === position).map(btn => ({
        event: that[btn.btnEvent],
        eventName: btn.btnEvent,
        text: btn.menuName,
        type: btn.btnStyle || (/remove/i.test(btn.btnEvent) ? 'danger': ''),
    })) ?? []
}

@Component
export default class TableRender extends FilterRender {
    @Ref()
    readonly ref!: VxeGridMethods
    pageTitle = ''
    current = 1
    loading = false
    size = 15
    total = 0
    defaultSize = 10
    noTablePadding = false // 表格不需要padding

    tableDefaultValue = '--'

    tableColumnConfigOld = () => [] as TableRenderColumnTypes<any>
    tableColumnConfig(): TableRenderColumnTypes<any> {
        return []
    }

    checkboxConfig = {} as VxeTablePropTypes.CheckboxConfig

    // 提供的表单简单插槽
    tableSlots = {
        dateformat: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            return (
                <div>
                    {dateFormat(row[column.field], column.params?.format || 'YYYY-MM-DD HH:mm')}
                </div>
            )
        },
        price: (params: VxeColumnSlotTypes.ContentSlotParams) => {
            const { row, column } = params
            return (
                <div class={`text-${column.params?.color || 'red'}`}>
                    ￥{ 
                        column.formatter ? (column as unknown as {
                            formatter: (params: VxeColumnSlotTypes.ContentSlotParams) => string
                        }).formatter(params) : row[column.field] }
                </div>
            )
        },
        unit: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            return (
                <div class={`${row[column.field] === this.tableDefaultValue ? '' : ''}`}>
                    {(row[column.field] || row[column.field] === 0) &&
                    row[column.field] !== this.tableDefaultValue
                        ? row[column.field] + column.params?.unit
                        : this.tableDefaultValue ?? ''}
                </div>
            )
        },
        color: (params: VxeColumnSlotTypes.ContentSlotParams) => {
            const { row, column } = params
            return (
                <div
                    class={`text-${column.params?.colors[row[column.params?.colorKey || column.field]] ?? ''}`}
                >
                    { 
                        column.formatter ? (column as unknown as {
                            formatter: (params: VxeColumnSlotTypes.ContentSlotParams) => string
                        }).formatter(params) : row[column.field] }
                </div>
            )
        },
        status: (params: VxeColumnSlotTypes.ContentSlotParams) => {
            const { row, column } = params
            const align = this.tableConfig().align ?? 'left' 
            return (
                <div class={`flex items-center ${align === 'left' ? 'justify-start' : align === 'right'? 'justify-end' :'justify-center'}` }>
                    <div class={`w-6px h-6px mr-4px rounded-full bg-${column.params?.colors[row[column.params?.statusKey || column.field]] ?? ''}`}></div>
                    { 
                        column.formatter ? (column as unknown as {
                            formatter: (params: VxeColumnSlotTypes.ContentSlotParams) => string
                        }).formatter(params) : row[column.field] }
                </div>
            )
        },
        colorTag: (params: VxeColumnSlotTypes.ContentSlotParams) => {
            const { row, column } = params
            return (
                <Tag
                    color={column.params?.tags[row[column.params?.tagKey || column.field]]}
                >
                    { 
                        column.formatter ? (column as unknown as {
                            formatter: (params: VxeColumnSlotTypes.ContentSlotParams) => string
                        }).formatter(params) : row[column.field] }
                </Tag>
            )
        },
        idcardAge: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            // 通过身份证号计算年龄
            return (
                <div>
                    {row[column.field]
                        ? Math.floor(
                            (new Date().getTime() -
                                  new Date(
                                      row[column.field].substr(6, 4),
                                      Number(row[column.field].substr(10, 2)) - 1,
                                      Number(row[column.field].substr(12, 2))
                                  ).getTime()) /
                                  (1000 * 60 * 60 * 24 * 365)
                        ) + '岁'
                        : ''}
                </div>
            )
        },
        idcard: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            const idcard = row[column.field]
            return <div>{idcard ? `${idcard.substring(0, 6)}${'*'.repeat(18 - 10)}${idcard.substring(idcard.length - 4)}` : '--'}</div>
        },
        enum: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            // 通过身份证号计算年龄
            return column.params?.enum[row[column.field]] || '--'
        },
        buttons: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            const user = useUserStore()
            const buttons = (column.params.buttons || []).filter((btn: TableRenderColumnParamsButtons<VxeTableDataRow>) => {
                // 需要隐藏 hidden?: (row: D) => boolean 返回一个boolean值
                return !btn?.hidden?.(row)
            })
            return buttons.map((button: TableRenderColumnParamsButtons<VxeTableDataRow>) => {
                const isConfirm = ref(false)
                const event = () => {
                    console.log(111, button.event, button)
                    if (column.params?.permission && !user.hasPermission(column.params?.permission)) {
                        message.error('暂无权限')
                        return 
                    }
                    if (button?.permission && !user.hasPermission(button?.permission)) {
                        message.error('暂无权限')
                        return 
                    }
                    button.event?.call(this, row)
                }
                return button.type !== 'danger' ? 
                    button.type === 'preview' ? <PreviewImageOrPdf src={row[button.previewProp as keyof typeof row]} text={button.text || '点击查看'} /> :
                        <Button class="!pl-0" onClick={() => event()} danger={button.type === 'danger'} type="link">{button.text}</Button>
                    : 
                    <Popconfirm
                        title={`${button.content ?? '确认删除吗？' }`}
                        onConfirm={() => event()}
                        v-slots={{
                            default: () => {
                                return <Button class="!pl-0" onClick={() => isConfirm.value = true}  danger={button.type === 'danger'} type="link">{button.text}</Button>
                            }
                        }}
                    >
                    </Popconfirm>
                    
            })
        },
        tooltip: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            const align = this.tableConfig().align ?? 'left' 
            return column.params?.tooltip?.text?.(row) ? <ToolTipText textAlign={align} link={column.params?.tooltip?.link} underline={column.params?.tooltip?.underline} prefixIcon={column.params?.tooltip?.prefixIcon} suffixIcon={column.params?.tooltip?.suffixIcon} text={column.params?.tooltip?.text?.(row)} content={column.params?.tooltip?.content?.(row)}></ToolTipText> : '--'
        },
        clickable: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            return <div class="text-blue-100 cursor-pointer" onClick={() => column.params?.event?.(row)}>{row[column.field]}</div>
        },
        toNext: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            return <div class="text-blue-100 cursor-pointer" onClick={() => {
                const user = useUserStore()
                if (column.params?.permission && !user.hasPermission(column.params?.permission)) {
                    message.error('暂无权限')
                    return 
                }
                router.push(column.params.path?.(row))
            }}>
                <div>{row[column.field]}</div>
            </div>
        },
        image: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            return row[column.field] && <ImageR width={column.params?.width ?? 60} height={column.params?.height ?? 60} src={row[column.field]} />
        },
        tooltipButtons: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            return <Tooltip v-slots= {{
                title: () => {
                    return(
                        <div class="px-10px text-center">
                            {
                                column.params?.buttons?.map((i: TableRenderColumnParamsButtons<VxeTableDataRow> ) => {
                                    return i.type === 'preview' ? <PreviewImageOrPdf type="white" hover src={row[i.previewProp as keyof typeof row]} text={i.text || '点击查看'} />:
                                        !i?.hidden?.(row) && <div class={`cursor-pointer hover:text-blue-100 my-8px ${i.type === 'danger' ? 'text-red': ''}`} onClick={i.event?.bind(this, row)}>{i.text}</div>
                                })
                            }
                        </div>
                    )
                },
                default: () => {
                    return <div>
                        <MoreOutlined />
                    </div>
                }
            }}>
            </Tooltip>
        },
        customer: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            return <div class="text-blue-100 cursor-pointer" onClick={() => column.params?.event?.(row)}>{row[column.field]}</div>
        },
        preview: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
            return column.params?.srcList?.(row)?.length ? <PreviewImageOrPdf src={column.params?.srcList?.(row)} text={column.params?.text || '点击查看'} /> : '--'
        }
    } as {
        [key: string]: (row: VxeColumnSlotTypes.ContentSlotParams) => JSX.Element
    }
    customTableSlots = {} as {
        [key: string]: (row: VxeColumnSlotTypes.ContentSlotParams) => JSX.Element
    }

    tableData = [] as any[]

    sortFields = [] as VxeGridDefines.SortChangeEventParams['sortList']

    

    tableConfig() {
        return {
            align: 'left',
            border: 'inner',
            height: 'auto',
            columnConfig: {
                minWidth: '100px'
            },
            showOverflow: true,
            showHeaderOverflow: true,
            showFooterOverflow: true,
            sortConfig: {
                remote: true
            }
        } as VxeGridProps
    }

    filterConfig() {
        return {} as FilterDto
    }
    filterBtnConfig() {
        return {
            search: {
                name: '空',
                element: 'empty',
                prefix: <div>
                    <Button type="primary" onClick={() => {
                        this.reloadPage(1)
                    }}>搜索</Button>
                    <Button class="ml-12" onClick={() => {
                        this.resetfilters()
                        this.reloadPage()
                    }}>清空条件</Button>
                </div>
            },
        } as FilterDto
    }

    // 刷新当前页
    async reloadPage(currentPage?: number) {
        this.current = typeof currentPage === 'number' ? currentPage : this.current
        const selected = this.ref?.getCheckboxRecords() || []
        // 删除时用，若删除后本页一条数据都没有并且不在第一页上，返回上一页
        if (this.tableData?.length - selected.length === 0 && this.current !== 1) {
            this.current--
        }
        await this.onPage(this.current)
    }

    nextPage() {
        console.log(this.current, 'currentcurrent')
        if (this.current * this.size >= this.total) return
        this.reloadPage(this.current + 1)
    }

    prevPage() {
        if (this.current <= 1) return
        this.reloadPage(this.current - 1 || 1)
    }

    // 获取筛选结果
    getFilterAndPages() {
        const params = super.getFilters()
        params.pageNum = this.current
        params.pageSize = this.size
        return params
    }

    // 分页逻辑
    async onPage(page: number) {
        this.current = page
        try {
            const result = (await this.onLoadData(
                page,
                this.size,
                this.getFilters()
            )) as any

            if (Object.prototype.hasOwnProperty.call(result, 'hasNextPage')) {
                this.tableData = result.list
                this.total = result.totalCount
            } else {
                if (result.total || result.total === 0) {
                    this.tableData = result.list || result.rows
                    // this.current = result.pageNum
                    // this.size = result.pageSize
                    this.total = result.total
                    if (!this.defaultSize) {
                        this.defaultSize = result.pageSize
                    }
                } else {
                    this.tableData = result
                }
            }

            this.loading = false
        } catch (e) {
            console.log(e)
            this.loading = false
        }
    }

    onLoadData(
        pageNum: number,       
        pageSize: number,
        filters: AnyObject
    ): Promise<PageDto<AnyObject>> | Promise<PageDto<AnyObject>> | Promise<any[]> | any[] {
        return []
    }

    onCheckboxChange(row: VxeGridDefines.CheckboxChangeEventParams) {}

    onCheckboxAll(row: VxeGridDefines.CheckboxChangeEventParams) {}

    onSortChange(params: VxeGridDefines.SortChangeEventParams) {
        if (!this.tableConfig().sortConfig?.remote) return
        this.sortFields = params.sortList
        this.reloadPage()
    }

    async onMounted() {
        // console.log('onMounted', this.$route)
        // 初始化筛选条件
        this.filters = {
            ...this.filterConfig(),
            ...this.filterBtnConfig()
        }
        this.onPage(1)
        
    }

    renderTabbar() {
        return <div></div>
    }
    renderButtons(type: ButtonMenuTypeCnEnum) {
        const buttons = renderSlotButtons(this, type)
        return buttons.map((button) => {
            const isConfirm = ref(false)
            const event = () => {
                button.event?.call(this, []) // 未来填充checkbox选中列表
            }
            return <Button onClick={() => event()} danger={button.type === 'danger'} type={button.type !== 'danger' && button.type ? button.type : undefined}>
                {button.eventName?.includes('Down') ? <CloudDownloadOutlined /> : ''}
                {button.eventName?.includes('Export') ? <DownloadOutlined /> : ''}
                {button.eventName?.includes('Upload') ? <CloudUploadOutlined /> : ''}
                {button.eventName?.includes('Remove') ? <DeleteOutlined /> : ''}
                {button.eventName?.includes('Add') ? <PlusOutlined /> : ''}
                {button.text}
            </Button>
                
        })
    }
    renderLeftBtns() {
        return <div class="gap-12 flex">{
            this.renderButtons(ButtonMenuTypeCnEnum.顶部左)
        }</div>
    }
    renderRightBtns() {
        return <div class="gap-12 flex">{
            this.renderButtons(ButtonMenuTypeCnEnum.顶部右)
        }</div>
    }

    renderStatistics() {
        return <></>
    }

    renderTitleBtn() {
        return <></>
    }

    renderTitle() {
        return this.pageTitle && <div class="flex justify-between px-20px pt-20px">
            <div class="font-bold text-lg">{this.pageTitle}</div>
            {this.renderTitleBtn()}
        </div>
    }

    renderToolbar() {
        return (
            <div class="flex justify-between mb-12 text-base mx-20">
                <div>
                    {this.renderLeftBtns()}
                </div>
                <div>
                    {this.renderRightBtns()}
                </div>
                {/* {this.renderStatistics()} */}
            </div>
        )
    }

    renderTable() {
        return (
            <div class={`h-full xs:h-full ${this.noTablePadding ? '' : 'p-20px'} overflow-auto overflow-hidden rounded-tl rounded-tr`}>
                <VxeGrid
                    ref="ref"
                    {...this.tableConfig()}
                    // columns={typeof this.tableColumnConfig === 'function' ? this.tableColumnConfig() : this.tableColumnConfigOld()}
                    columns={ [...this.tableColumnConfigOld(), ...this.tableColumnConfig()]}
                    data={this.tableData}
                    checkboxConfig={this.checkboxConfig}
                    onCheckboxChange={this.onCheckboxChange.bind(this)}
                    onCheckboxAll={this.onCheckboxAll.bind(this)}
                    onSortChange={this.onSortChange.bind(this)}
                    v-slots={{
                        ...this.tableSlots,
                        ...this.customTableSlots,
                        empty: () => {
                            return <Empty/>
                        }
                    }}
                    headerCellClassName={(params) => {
                        return 'bg-fill'
                    }}
                />
            </div>
        )
    }
    renderVxePager() {
        return (
            <Pagination v-model:current={this.current} total={this.total} onChange={this.onPage} showQuickJumper v-model:pageSize={this.size} />

        )
    }
    renderPager() {
        return (
            this.total ? <div class="px-20px pb-20px flex justify-between items-center">
                <div class="text-base">
                    共 {this.total} 条，1页{this.size}条
                </div>
                {this.renderVxePager()}
            </div> : ''
        )
    }

    renderElements() {
        return (
            <div class="md:flex md:flex-col h-full">
                {this.renderTitle()}
                {this.renderTabbar()}
                <Form class="mb1-12" onSubmit={this.reloadPage.bind(this, 1)}>
                    {
                        this.renderFilter()
                    }
                    <button type='submit' class="hidden"></button>
                </Form>
                {this.renderToolbar()}
                {this.renderTable()}
                {this.renderPager()}
            </div>
        )
    }

    renderNoFilterTable() {
        return (
            <div class="md:flex md:flex-col h-full">
                {this.renderTitle()}
                {this.renderTabbar()}
                {this.renderToolbar()}
                {this.renderTable()}
                {this.renderPager()}
            </div>
        )
    }

    render() {
        return this.renderElements()
    }
}
